package com.azt.utils;

import org.apache.log4j.Logger;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Properties;

import static com.azt.utils.KuaiQianPay.PAY_PROP;

/**
 * 快钱支付加密工具类
 * */
public class Pkipair {

    private static final Logger LOGGER = Logger.getLogger(Pkipair.class);

    public String signMsg(String signMsg) {
        String base64 = "";
        try {
            // 密钥仓库
            KeyStore ks = KeyStore.getInstance("PKCS12");

            // 读取密钥仓库（相对路径）在线测试切换
            String file = "";
            char[] keyPwd;
            Properties prop = PropertiesLoaderUtils.loadAllProperties(PAY_PROP);
            //支付环境： 0. 测试  1. 生产
            int payEnv = CommonUtil.safeToInt(prop.getProperty("payEnv", "0"), 0);
            LOGGER.info("payEnv：" + payEnv);
            //正式环境
            if(payEnv == 1){
                file = Pkipair.class.getResource("/pay/kuaiqian/99bill-rsa.pfx").getPath().replaceAll("%20", " ");
                keyPwd = "azt365".toCharArray();
            }else{
                //测试环境
                file = Pkipair.class.getResource("/pay/kuaiqian/99bill-rsa.pfx").getPath().replaceAll("%20", " ");
                keyPwd = "123456".toCharArray();
            }

            FileInputStream ksfis = new FileInputStream(file);

            BufferedInputStream ksbufin = new BufferedInputStream(ksfis);

            ks.load(ksbufin, keyPwd);
            // 从密钥仓库得到私钥
            PrivateKey priK = (PrivateKey) ks.getKey("test-alias", keyPwd);
            Signature signature = Signature.getInstance("SHA1withRSA");
            signature.initSign(priK);
            signature.update(signMsg.getBytes("utf-8"));
            sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
            base64 = encoder.encode(signature.sign());

        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        LOGGER.info("signMsg = " + base64);
        return base64;
    }

    public boolean enCodeByCer( String val, String msg) {
        boolean flag = false;
        try {

            //获得文件(相对路径) 在线测试切换
            String file;

            Properties prop = PropertiesLoaderUtils.loadAllProperties(PAY_PROP);
            //支付环境： 0. 测试  1. 生产
            int payEnv = CommonUtil.safeToInt(prop.getProperty("payEnv", "0"), 0);
            LOGGER.info("payEnv：" + payEnv);

            //正式环境
            if(payEnv == 1){
                file = Pkipair.class.getResource("/pay/kuaiqian/production/99bill-rsa.cer").toURI().getPath();
            }else{
                //测试环境
                file = Pkipair.class.getResource("/pay/kuaiqian/test/99bill[1].cert.rsa.20140803.cer").toURI().getPath();
            }
            FileInputStream inStream = new FileInputStream(file);

            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
            //获得公钥
            PublicKey pk = cert.getPublicKey();
            //签名
            Signature signature = Signature.getInstance("SHA1withRSA");
            signature.initVerify(pk);
            signature.update(val.getBytes());
            //解码
            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            flag = signature.verify(decoder.decodeBuffer(msg));
        } catch (Exception e) {
            LOGGER.error("enCodeByCer error", e);
        }
        return flag;
    }
}
